<?php namespace Admin\Model;

use Hdphp\Model\Model;

/**
 *管理员模型
 */

class Admin extends Model{

	protected $table="shop_admin";

	//自动验证
	
	protected $validate = array( 
        // array('cat_name','required','栏目名称不能为空',3,3),
    ); 

    //登录
    public function login(){
    	if(isset($_POST['code']) && strtoupper($_POST['code'])!=$_SESSION['code'])
    	{
    		$this->error="验证码错误";
    		return false;
    	}
    	if(empty($_POST['username']))
    	{
    		$this->error="账户不能为空";
    		return false;
    	}

    	$admin=$this->where('username',$_POST['username'])->first();
    	if(!$admin)
    	{
    		$this->error="账户不存在";
    		return false;
    	}
    	if($admin['password']!==md5($_POST['password']))
    	{
    		$this->error="密码错误";
    		return false;
    	}

    	$data['admin_id']=$admin['admin_id'];
    	$data['login_at']=time();
    	$data['login_ip']=$_SERVER['REMOTE_ADDR'];
    	$this->save($data);
    	$_SESSION['admin_id']=$admin['admin_id'];
    	$_SESSION['username']=$admin['username'];
    	return true;
    }

    //修改密码
    
    public function changPassword()
    {

    	$this->validate=array(
            array('password','required','密码不能为空',3,3),
            array('password','confirm:password_c','两次密码不一致',3,3),
            array('old_password','required','原密码不能为空',3,3),
        );

        //旧密码的判断
        $oldPassword = $this->where('admin_id',$_SESSION['admin_id'])->pluck('password');
        if(md5($_POST['old_password'])!==$oldPassword)
        {
            $this->error ='原密码输入错误';
            return false;
        }
        // $this->data=$_POST
        if($this->create())
        {
            //更新需要主键值 
            $_POST['admin_id']=$_SESSION['admin_id'];
            $_POST['password']=md5($_POST['password']);
            unset($_POST['old_password']);
            unset($_POST['password_c']);
            return $this->save($_POST);
        }

    }




}